import { DiningModel } from '../models/dining.js';

export const DiningController = {
  async getAllMenuItems(req, res) {
    try {
      const items = await DiningModel.getAllMenuItems();
      res.json(items);
    } catch (error) {
      console.error('Error in getAllMenuItems controller:', error);
      res.status(500).json({ error: 'Failed to fetch menu items' });
    }
  },

  async createMenuItem(req, res) {
    try {
      const id = await DiningModel.createMenuItem(req.body);
      const newItem = {
        id,
        ...req.body,
        createdAt: new Date(),
        updatedAt: new Date()
      };
      res.status(201).json(newItem);
    } catch (error) {
      console.error('Error in createMenuItem controller:', error);
      res.status(500).json({ error: 'Failed to create menu item' });
    }
  },

  async updateMenuItem(req, res) {
    try {
      const success = await DiningModel.updateMenuItem(req.params.id, req.body);
      if (success) {
        const updatedItem = {
          id: parseInt(req.params.id),
          ...req.body,
          updatedAt: new Date()
        };
        res.json(updatedItem);
      } else {
        res.status(404).json({ error: 'Menu item not found' });
      }
    } catch (error) {
      console.error('Error in updateMenuItem controller:', error);
      res.status(500).json({ error: 'Failed to update menu item' });
    }
  },

  async getNutritionAnalysis(req, res) {
    try {
      const analysis = await DiningModel.getNutritionAnalysis();
      res.json(analysis);
    } catch (error) {
      console.error('Error in getNutritionAnalysis controller:', error);
      res.status(500).json({ error: 'Failed to get nutrition analysis' });
    }
  }
};